/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package view.promo;

import java.awt.Color;
import java.awt.Component;
import java.awt.KeyboardFocusManager;
import java.awt.event.ActionEvent;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Date;
import java.util.List;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.BorderFactory;
import javax.swing.DefaultCellEditor;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
import javax.swing.SwingConstants;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableCellRenderer;
import main.ServicesList;
import model.inventory.Item;
import model.inventory.ItemHpp;
import model.inventory.ItemPrice;
import model.promo.Promo;
import model.promo.PromoPrice;
import model.promo.PromoPriceId;
import org.apache.log4j.Logger;
import utility.Constants;
import utility.StringUtils;
import utility.com.CheckboxTableRenderer;
import utility.com.TableCellListener;
import utility.com.TableUtil;
import utility.com.TextComponentUtils;
import view.DialogTemplate;
import view.lookup.LookupSimpleFrm;

/**
 *
 * @author jay
 */
public class PromoPriceFrm extends DialogTemplate {

    private static final int COL_NO  = 0;
    private static final int COL_PLU = 1;
    private static final int COL_NAMA = 2;
    private static final int COL_PURCHASE = 3;
    private static final int COL_SALES = 4;
    private static final int COL_MARGIN = 5;
    private static final int COL_MARKUP = 6;
    private static final int COL_PRICE  = 7;
    private static final int COL_UPDATED  = 8;
    
    final JTextField pluCE = new JTextField();
    final JTextField marginCE = new JTextField();
    final JTextField markupCE = new JTextField();
    final JTextField priceCE = new JTextField();
    
    private DefaultTableCellRenderer rightCR = new DefaultTableCellRenderer();
    private TableCellListener tableCellListener;

    private Promo promo;
    
    private PromoPriceTM tableModel;
    private List<PromoPrice> promoPrices;

    private static Logger log = Logger.getLogger(PromoPriceFrm.class);
    private Object oldValue, newValue;
    
    public PromoPriceFrm() {
        super(ServicesList.MAIN_FRAME, true);
        initComponents();
        initComponentsRules();
    }

    class ActionKeyListener implements KeyListener {
        @Override public void keyTyped(KeyEvent e) {} 
        @Override public void keyReleased(KeyEvent e) {}
        @Override public void keyPressed(KeyEvent e) {
            switch (e.getKeyCode()) { 
                case KeyEvent.VK_F2: 
                    switch(e.getComponent().getName()) {
                        case "pluCE": 
                            lookupMaster(pluCE.getText()); 
                            break;
                    };
                break;  
                
                case KeyEvent.VK_ENTER: 
                    switch(e.getComponent().getName()) {
                        case "pluCE": 
                            newValue = pluCE.getText();
                            if (!newValue.equals(oldValue)) { getMaster(pluCE.getText()); }
                            break;
                       default: moveNext(); break;
                    };
                break;      
            }
        }
    }
    
    class ActionFocusGained implements FocusListener {
        @Override public void focusGained(FocusEvent e) { 
            Component componen = (Component) e.getSource(); 
            if (componen instanceof JTextField) { oldValue = ((JTextField) componen).getText();}
        }
        
        @Override public void focusLost(FocusEvent e) {
            Component componen = (Component) e.getSource(); 
            if (componen instanceof JTextField) { newValue = ((JTextField) componen).getText();}
            if (!newValue.equals(oldValue)) { initButtonState(true); }
        }
    }

    class GridKeyListener implements KeyListener {
        @Override public void keyTyped(KeyEvent e) {};
        @Override public void keyReleased(KeyEvent e) {};
        
        @Override public void keyPressed(KeyEvent e) {
            switch (e.getKeyCode()) { 
                case KeyEvent.VK_ENTER:
                    if (grid.getSelectedColumn() == COL_PRICE) {
                        saveData();
                        if (grid.getSelectedRow() == grid.getRowCount()-1) {
                            promoPrices.add(new PromoPrice());
                        }
                        tableModel.fireTableDataChanged(); 
                    }
                    break;
            }        
        };
    }
    
    Action DetailAction = new AbstractAction() {
        @Override
        public void actionPerformed(ActionEvent e) {
            TableCellListener tblCellListener = (TableCellListener)e.getSource();
            int row = tblCellListener.getRow();
            int col = tblCellListener.getColumn();
                
            Object oldVal = tblCellListener.getOldValue();
            Object newVal = tblCellListener.getNewValue();
            
            if(oldVal==null) {oldVal="";}
            if(newVal==null) {newVal="";}
                
            if (!oldVal.equals(newValue)) {
                switch (col) {
                    case COL_MARGIN: 
                        BigDecimal mrg = TextComponentUtils.parseNumberToBigDecimal((String)newVal);
                        promoPrices.get(row).setMargin(mrg);
                        calculate(row, col);
                        initButtonState(true);
                        break;
                    case COL_MARKUP: 
                        BigDecimal makup = TextComponentUtils.parseNumberToBigDecimal((String)newVal);
                        promoPrices.get(row).setMargin(makup);
                        calculate(row, col);
                        initButtonState(true);
                        break;
                    case COL_PRICE: 
                        BigDecimal price = TextComponentUtils.parseNumberToBigDecimal((String)newVal);
                        promoPrices.get(row).setMargin(price);
                        calculate(row, col);
                        initButtonState(true);
                        break;
                }
            }
        }
    };     

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        txtNama = new javax.swing.JTextField();
        chkMember = new javax.swing.JCheckBox();
        chkNonMember = new javax.swing.JCheckBox();
        jLabel7 = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jPanel1 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        grid = new javax.swing.JTable();
        btnSave = new javax.swing.JButton();
        btnClose = new javax.swing.JButton();
        txtEndDate = new javax.swing.JFormattedTextField();
        txtStartDate = new javax.swing.JFormattedTextField();
        btnNew = new javax.swing.JButton();
        btnDelete = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        txtNama.setEnabled(false);
        txtNama.setFocusable(false);
        txtNama.setName("txtNama"); // NOI18N

        chkMember.setText("Member");
        chkMember.setEnabled(false);
        chkMember.setFocusable(false);
        chkMember.setName("chkMember"); // NOI18N

        chkNonMember.setText("Non Member");
        chkNonMember.setEnabled(false);
        chkNonMember.setFocusable(false);
        chkNonMember.setName("chkNonMember"); // NOI18N

        jLabel7.setText("Berlaku Untuk :");

        jLabel1.setText("Nama :");

        jLabel2.setText("Dari Tgl :");

        jLabel5.setText("Sampai :");

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Item"));

        grid.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null}
            },
            new String [] {
                "PLU", "Nama", "Hrg Beli", "Hrg Normal", "Mrg", "Mrkup", "Hrg Promo"
            }
        ));
        jScrollPane1.setViewportView(grid);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 672, Short.MAX_VALUE)
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 366, javax.swing.GroupLayout.PREFERRED_SIZE)
        );

        btnSave.setText("Simpan");
        btnSave.setName("btnSave"); // NOI18N
        btnSave.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSaveActionPerformed(evt);
            }
        });

        btnClose.setText("Keluar");
        btnClose.setName("btnClose"); // NOI18N
        btnClose.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCloseActionPerformed(evt);
            }
        });

        txtEndDate.setText("01/03/2012 00:00");
        txtEndDate.setEnabled(false);
        txtEndDate.setFocusable(false);
        txtEndDate.setName("txtEndDate"); // NOI18N

        txtStartDate.setText("01/03/2012 00:00");
        txtStartDate.setEnabled(false);
        txtStartDate.setFocusable(false);
        txtStartDate.setName("txtStartDate"); // NOI18N

        btnNew.setText("Tambah");
        btnNew.setName("btnSave"); // NOI18N
        btnNew.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnNewActionPerformed(evt);
            }
        });

        btnDelete.setText("Hapus");
        btnDelete.setName("btnSave"); // NOI18N
        btnDelete.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnDeleteActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(btnDelete)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnNew)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnSave)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnClose)
                .addContainerGap())
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel7)
                    .addComponent(jLabel2)
                    .addComponent(jLabel1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(chkMember, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(chkNonMember)
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(txtNama, javax.swing.GroupLayout.PREFERRED_SIZE, 316, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(txtStartDate, javax.swing.GroupLayout.PREFERRED_SIZE, 102, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(jLabel5)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(txtEndDate, javax.swing.GroupLayout.PREFERRED_SIZE, 102, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtNama, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(txtStartDate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel5)
                    .addComponent(txtEndDate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel7)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(chkMember)
                        .addComponent(chkNonMember)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnSave)
                    .addComponent(btnClose)
                    .addComponent(btnNew)
                    .addComponent(btnDelete))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSaveActionPerformed
        saveData();
    }//GEN-LAST:event_btnSaveActionPerformed

    private void btnNewActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnNewActionPerformed
        addNewRow();
    }//GEN-LAST:event_btnNewActionPerformed

    private void btnDeleteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDeleteActionPerformed
        deleteRow();
    }//GEN-LAST:event_btnDeleteActionPerformed

    private void btnCloseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCloseActionPerformed
        dispose();
    }//GEN-LAST:event_btnCloseActionPerformed
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnClose;
    private javax.swing.JButton btnDelete;
    private javax.swing.JButton btnNew;
    private javax.swing.JButton btnSave;
    private javax.swing.JCheckBox chkMember;
    private javax.swing.JCheckBox chkNonMember;
    private javax.swing.JTable grid;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JFormattedTextField txtEndDate;
    private javax.swing.JTextField txtNama;
    private javax.swing.JFormattedTextField txtStartDate;
    // End of variables declaration//GEN-END:variables

    @Override
    public int execute(int id) {
        setLocationRelativeTo(null);
        promo = ServicesList.getPromoService().getPromo(id);
        initForm();
        setVisible(true);
        return 0; 
    }

    @Override
    protected void initForm() {
        if (promo != null) {
            txtNama.setText(promo.getPromoName());
           
            String whois = promo.getWhois();
            if (whois == null || whois.isEmpty()) {
                whois = "00";
            }

            chkMember.setSelected("1".equals(whois.substring(0, 1)) ? true:false);
            chkNonMember.setSelected("1".equals(whois.substring(1, 2)) ? true:false);
            txtStartDate.setText(StringUtils.formatDateTime24(promo.getStartDate()));
            txtEndDate.setText(StringUtils.formatDateTime24(promo.getEndDate()));
            loadData(promo.getId());
        }
    }

    @Override
    protected void loadData(int id) {
        grid.removePropertyChangeListener(tableCellListener);
        promoPrices = ServicesList.getPromoPriceService().getAll(id);
        if (promoPrices.isEmpty()) {
            promoPrices.add(new PromoPrice());
        }
        
        tableModel = new PromoPriceTM(promoPrices);
        grid.setModel(tableModel);
                     
        grid.getColumnModel().getColumn(COL_PLU).setCellEditor(new DefaultCellEditor (pluCE));
        grid.getColumnModel().getColumn(COL_MARGIN).setCellEditor(new DefaultCellEditor (marginCE));
        grid.getColumnModel().getColumn(COL_MARKUP).setCellEditor(new DefaultCellEditor (markupCE));
        grid.getColumnModel().getColumn(COL_PRICE).setCellEditor(new DefaultCellEditor (priceCE));
        grid.getColumnModel().getColumn(COL_UPDATED).setCellRenderer(new CheckboxTableRenderer());
        
        grid.getColumnModel().getColumn(COL_NO).setCellRenderer(rightCR);
        grid.getColumnModel().getColumn(COL_MARGIN).setCellRenderer(rightCR);
        grid.getColumnModel().getColumn(COL_MARKUP).setCellRenderer(rightCR);
        grid.getColumnModel().getColumn(COL_PRICE).setCellRenderer(rightCR);
        grid.getColumnModel().getColumn(COL_PURCHASE).setCellRenderer(rightCR);
        grid.getColumnModel().getColumn(COL_SALES).setCellRenderer(rightCR);
        
        grid.getColumnModel().getColumn(COL_PLU).setMaxWidth(50);
        grid.getColumnModel().getColumn(COL_NO).setMaxWidth(30);
        grid.getColumnModel().getColumn(COL_MARGIN).setMaxWidth(40);
        grid.getColumnModel().getColumn(COL_MARKUP).setMaxWidth(65);
        grid.getColumnModel().getColumn(COL_PRICE).setMaxWidth(65);
        grid.getColumnModel().getColumn(COL_PURCHASE).setMaxWidth(65);
        grid.getColumnModel().getColumn(COL_SALES).setMaxWidth(65);
        grid.getColumnModel().getColumn(COL_UPDATED).setMaxWidth(30);
        
        grid.getColumnModel().getColumn(COL_PLU).setMinWidth(50);
        grid.getColumnModel().getColumn(COL_NO).setMinWidth(30);
        grid.getColumnModel().getColumn(COL_MARGIN).setMinWidth(40);
        grid.getColumnModel().getColumn(COL_MARKUP).setMinWidth(60);
        grid.getColumnModel().getColumn(COL_PRICE).setMinWidth(60);
        grid.getColumnModel().getColumn(COL_PURCHASE).setMinWidth(60);
        grid.getColumnModel().getColumn(COL_SALES).setMinWidth(60);
        grid.getColumnModel().getColumn(COL_UPDATED).setMinWidth(0);
        grid.getColumnModel().getColumn(COL_UPDATED).setMinWidth(0);
        grid.getColumnModel().getColumn(COL_UPDATED).setPreferredWidth(30);
        
        grid.setGridColor(Color.LIGHT_GRAY);
        setTableLookStyle();
        tableCellListener = new TableCellListener(grid, DetailAction);
    }

    @Override
    protected void saveData() {
        int row = grid.getSelectedRow();
        PromoPrice p  = promoPrices.get(row);
        
        if (p.getItem().getId() > 0 &&  p.getUpdated()) {
            try{
                ServicesList.getPromoPriceService().save(p);
                p.setUpdated(false);
                tableModel.fireTableRowsUpdated(row, row);
                
            } catch(Exception ex){
                log.error(ex);
                JOptionPane.showMessageDialog(this, "Data gagal disimpan.", "Error",JOptionPane.ERROR_MESSAGE);
            }
        }
    }

    @Override
    protected void validasi() {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    protected void moveNext() {
        KeyboardFocusManager manager = KeyboardFocusManager.getCurrentKeyboardFocusManager();
        manager.focusNextComponent();
    }

    @Override
    protected void initButtonState(boolean status) {
        //throw new UnsupportedOperationException("Not supported yet.");
    }
        
    private void initComponentsRules() {
        
        btnNew.registerKeyboardAction(btnNew.getActionForKeyStroke(
            KeyStroke.getKeyStroke(KeyEvent .VK_SPACE, 0, false)), KeyStroke.getKeyStroke(KeyEvent .VK_ENTER, 0, false), JComponent.WHEN_FOCUSED);
 
        btnNew.registerKeyboardAction(btnNew.getActionForKeyStroke(
            KeyStroke.getKeyStroke(KeyEvent .VK_SPACE, 0, true)), KeyStroke.getKeyStroke(KeyEvent .VK_ENTER, 0, true), JComponent.WHEN_FOCUSED);
        
        btnDelete.registerKeyboardAction(btnDelete.getActionForKeyStroke(
            KeyStroke.getKeyStroke(KeyEvent .VK_SPACE, 0, false)), KeyStroke.getKeyStroke(KeyEvent .VK_ENTER, 0, false), JComponent.WHEN_FOCUSED);

        btnDelete.registerKeyboardAction(btnDelete.getActionForKeyStroke(
            KeyStroke.getKeyStroke(KeyEvent .VK_SPACE, 0, true)), KeyStroke.getKeyStroke(KeyEvent .VK_ENTER, 0, true), JComponent.WHEN_FOCUSED);

        btnSave.registerKeyboardAction(btnSave.getActionForKeyStroke(
            KeyStroke.getKeyStroke(KeyEvent .VK_SPACE, 0, false)), KeyStroke.getKeyStroke(KeyEvent .VK_ENTER, 0, false), JComponent.WHEN_FOCUSED);
 
        btnSave.registerKeyboardAction(btnSave.getActionForKeyStroke(
            KeyStroke.getKeyStroke(KeyEvent .VK_SPACE, 0, true)), KeyStroke.getKeyStroke(KeyEvent .VK_ENTER, 0, true), JComponent.WHEN_FOCUSED);
        
        btnClose.registerKeyboardAction(btnClose.getActionForKeyStroke(
            KeyStroke.getKeyStroke(KeyEvent .VK_SPACE, 0, false)), KeyStroke.getKeyStroke(KeyEvent .VK_ENTER, 0, false), JComponent.WHEN_FOCUSED);
 
        btnClose.registerKeyboardAction(btnClose.getActionForKeyStroke(
            KeyStroke.getKeyStroke(KeyEvent .VK_SPACE, 0, true)), KeyStroke.getKeyStroke(KeyEvent .VK_ENTER, 0, true), JComponent.WHEN_FOCUSED);
        
        rightCR.setHorizontalAlignment(SwingConstants.RIGHT);   
        
        marginCE.setHorizontalAlignment(SwingConstants.RIGHT);
        markupCE.setHorizontalAlignment(SwingConstants.RIGHT);
        priceCE.setHorizontalAlignment(SwingConstants.RIGHT);
        
        TextComponentUtils.setCurrency(marginCE);
        TextComponentUtils.setCurrency(markupCE);
        TextComponentUtils.setCurrency(priceCE);
                
        pluCE.setName("pluCE");

        pluCE.addKeyListener(new ActionKeyListener());
        pluCE.addFocusListener(new ActionFocusGained());
   
        TableUtil.setTableActionKeyMap(grid);
        grid.addKeyListener( new GridKeyListener());
    }
    
    private void setMaster(Object object) {
         if (object != null) {
            
             boolean isItemInDetails = false;
             int row = 0;
             int itemId = ((Item) object).getId();
             for (PromoPrice detail: promoPrices) {
                if(detail.getItem().getId()== itemId) {
                    isItemInDetails=true;
                    break;
                } row++;
             }
                    
             if (isItemInDetails) {
                JOptionPane.showMessageDialog(this, "Barang sudah ada.", "Informasi",JOptionPane.INFORMATION_MESSAGE);
                grid.setRowSelectionInterval(row, row);
                grid.setColumnSelectionInterval(COL_PLU, COL_PLU);
                grid.requestFocus();
                        
             }else {
                row = grid.getSelectedRow();
                promoPrices.get(row).setUpdated(true);
                
                promoPrices.get(row).setItem((Item) object);
                promoPrices.get(row).setPromo(promo);
                promoPrices.get(row).setId(new PromoPriceId(promo.getId(), itemId));

                //cari juga hpp
                ItemHpp hpp = ServicesList.getItemHppService().get(itemId, new Date()); 
                if (hpp==null) {
                    JOptionPane.showMessageDialog(this, "Harga beli belum diseting.", "Error",JOptionPane.ERROR_MESSAGE);
                } else {
                    promoPrices.get(row).setCostPrice(hpp.getHppAfterPpn());
                    calculate(row, COL_MARGIN);
                }

                ItemPrice price = ServicesList.getItemPriceService().get(itemId, 1, new Date()); 
                if (price!=null) {
                    promoPrices.get(row).setSalesPrice(price.getPrice());
                }
                 tableModel.fireTableRowsUpdated(row, row);
             }    
        }
    }
    
    private void lookupMaster(String param) {
        Object object = new LookupSimpleFrm().execute(Constants.LOOKUP_ITEM, param); 
        if (object != null) { setMaster(object); }
    }
    
    private void getMaster(String kode) {
        Item item = ServicesList.getItemService().getItem(kode);
        if (item != null) {setMaster(item); }
        else { lookupMaster(pluCE.getText()); }
    }
    
    private void calculate(int row, int col) {
        BigDecimal margin = promoPrices.get(row).getMargin();
        BigDecimal markup = promoPrices.get(row).getMarkup();
        BigDecimal price = promoPrices.get(row).getPrice();
        BigDecimal costPrice = promoPrices.get(row).getCostPrice();
            
        if (col==COL_MARGIN) {
            margin = margin.divide(Constants.PERSENT_DIVIDER, 2, RoundingMode.HALF_EVEN);
            price = margin.multiply(costPrice).setScale(0, RoundingMode.HALF_EVEN).add(costPrice);
            markup = price.subtract(costPrice).setScale(2, RoundingMode.HALF_EVEN);
                
            promoPrices.get(row).setMarkup(markup);
            promoPrices.get(row).setPrice(price);

        } else if (col==COL_MARKUP) {
            price = costPrice.add(markup);
            margin = price.subtract(costPrice).divide(costPrice).multiply(Constants.PERSENT_DIVIDER).setScale(2, RoundingMode.HALF_EVEN);
            promoPrices.get(row).setMargin(margin);
            promoPrices.get(row).setPrice(price);

        }else if (col==COL_PRICE) {
            markup = price.subtract(costPrice).setScale(2, RoundingMode.HALF_EVEN);
            margin = price.subtract(costPrice).divide(costPrice).multiply(Constants.PERSENT_DIVIDER).setScale(2, RoundingMode.HALF_EVEN);
            promoPrices.get(row).setMargin(margin);
            promoPrices.get(row).setMarkup(markup);
        }
        promoPrices.get(row).setUpdated(true);   
        tableModel.fireTableRowsUpdated(row, row);
    }
    
    private void deleteRow () {
        int rowCount = grid.getRowCount();
        int row = grid.getSelectedRow();
        
        PromoPrice deletedData = promoPrices.get(row);
        boolean saved = ServicesList.getPromoPriceService().delete(deletedData);
        if (!saved) {
            JOptionPane.showMessageDialog(this, "Data gagal dihapus.", "Error",JOptionPane.ERROR_MESSAGE);
        
        }else {
        
            if (rowCount==1) {
                promoPrices.set(row, new PromoPrice());
                tableModel.fireTableRowsUpdated(row, row);
            } else {
                promoPrices.remove(row);
                tableModel.fireTableRowsDeleted(row, row);
            }
        }
    }
    
    private void addNewRow () {
        tableModel.add(new PromoPrice());
        grid.setRowSelectionInterval(grid.getRowCount()-1, grid.getRowCount()-1);
    }
    
    private void setTableLookStyle() {
        
        final TableCellRenderer header = grid.getTableHeader().getDefaultRenderer();
        grid.getTableHeader().setDefaultRenderer(new TableCellRenderer() {

            @Override
            public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
                JLabel lbl = (JLabel) header.getTableCellRendererComponent(table, 
                      value, isSelected, hasFocus, row, column);
                
                lbl.setBorder(BorderFactory.createEmptyBorder(5,2,5,2));  
                switch (column) {
                    case COL_PLU: lbl.setHorizontalAlignment(SwingConstants.LEFT); break;
                    case COL_NAMA: lbl.setHorizontalAlignment(SwingConstants.LEFT); break;
                    default: lbl.setHorizontalAlignment(SwingConstants.RIGHT); break;   
                }
                
                lbl.setForeground(Color.WHITE);
                lbl.setBackground(Color.DARK_GRAY);
                    
                return lbl;
            }
        });
        
    }
}
